package com.centerm.structure.api;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.centerm.common.constant.Constant;
import com.centerm.common.constant.error.GlobalErrorEnum;
import com.centerm.common.constant.validate.Delete;
import com.centerm.common.constant.validate.Insert;
import com.centerm.common.constant.validate.Update;
import com.centerm.common.view.JSONResponse;
import com.centerm.common.view.page.DefaultPage;
import com.centerm.common.view.page.PageQueryParam;
import com.centerm.common.view.page.PageQueryResult;
import com.centerm.structure.domain.Permission;
import com.centerm.structure.domain.User;
import com.centerm.structure.dto.UserInfo;
import com.centerm.structure.dto.UserRoleInfo;
import com.centerm.structure.service.DepartmentService;
import com.centerm.structure.service.PermissionService;
import com.centerm.structure.service.UserRoleService;
import com.centerm.structure.service.UserService;

@RestController
@RequestMapping("user")
public class UserAPI extends AbstractAPI {
	@Autowired
	private UserService userService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private PermissionService permissionService;

	/**
	 * 用户登录
	 * 
	 * @author czy
	 * @date 2017年8月14日
	 * @param uid
	 *            :用户名，password:密码
	 * @return true or false
	 */
	@RequestMapping("login")
	public JSONResponse<List<Permission>> userLogin(HttpSession httpSession,
			@RequestBody UserInfo userInfo) {
		String uid = userInfo.getUid();
		String password = userInfo.getPassword();
		if (StringUtils.isBlank(uid) || StringUtils.isBlank(password)) {
			// 参数检查异常
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		// 登录的帐号必须有效
		userInfo.setValid(1);
		List<User> list = userService.listByParam(userInfo);
		if (list == null || list.size() != 1) {
			return new JSONResponse<>(GlobalErrorEnum.LOGIN_ERROR);
		}
		User user = list.get(0);
		List<String> permissionList = permissionService
				.listUserPermsssionCode(user.getId());
		// 保存用户信息、权限信息到session
		httpSession.setAttribute(Constant.SESSION_USER, user);
		httpSession.setAttribute(Constant.SESSION_PERMISSION, permissionList);
		return success(permissionService.listUserPermsssion(user.getId()));
	}

	/**
	 * 注销用户
	 * 
	 * @author czy
	 * @date 2017年8月14日
	 * @param
	 * @return
	 */
	@RequestMapping("cancellation")
	public JSONResponse<Boolean> cancellation(@RequestBody UserInfo userInfo,
			HttpSession httpSession) {
		String uid = userInfo.getUid();
		if (StringUtils.isBlank(uid)) {
			// 参数检查异常
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		httpSession.removeAttribute(Constant.SESSION_USER);
		httpSession.removeAttribute(Constant.SESSION_PERMISSION);
		return success(true);
	}

	/**
	 * 验证用户帐号是否存在
	 * 
	 * @author czy
	 * @date 2017年8月14日
	 * @param
	 * @return
	 */
	@RequestMapping("existUid")
	public JSONResponse<Boolean> existUid(@RequestBody UserInfo userInfo) {
		String uid = userInfo.getUid();
		if (StringUtils.isBlank(uid)) {
			// 参数检查异常
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		return success(userService.existUid(uid));
	}


    /**
     * @Description 根据部门获取部门下所有人员列表（包括子部门下的人员）
     * @author lk
     * @date 2017年8月30日
     * @param departmentInfo
     * @return
     */
    @RequestMapping("listDepartmentMember")
    public JSONResponse<List<UserInfo>> listDepartmentMember(
            @RequestBody UserInfo userInfo) {
        if(userInfo.getDepartment() == null) {
            logger.error("获取部门人员信息异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
            return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
        } else {
            List<Integer> deparmentIdList = departmentService.listDepartmentIdByParentId(userInfo.getDepartment());
            List<UserInfo> userList = userService.listDepartmentMember(userInfo, deparmentIdList);
            return success(userList);
        }
    }

	/**
	 * 根据条件分页查询用户列表
	 * 
	 * @author czy
	 * @date 2017年8月14日
	 * @param
	 * @return
	 */
	@PostMapping("page/byParam")
	public JSONResponse<PageQueryResult<UserInfo>> pageUserByParam(
			@RequestBody PageQueryParam<UserInfo> param) {
		DefaultPage page = param.getPage();
		UserInfo userInfo = param.getParam();
		if (page == null || userInfo == null) {
			// 参数检查异常
			logger.debug("PARAM_ERROR：" + param.toString());
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		List<Integer> departmentIdList = null;
		if(userInfo.getDepartment() != null) {
		    departmentIdList = departmentService.listDepartmentIdByParentId(userInfo.getDepartment());
		}
		
		// 分页查询
		PageQueryResult<UserInfo> queryResult = userService.pageUserInfoList(
				page.getPageNum() == null ? Constant.DEFAULT_PAGENUM : page
						.getPageNum(),
				page.getPageSize() == null ? Constant.DEFAULT_PAGESIZE : page
						.getPageSize(), userInfo, departmentIdList);
		return success(queryResult);
	}

	/**
	 * 新增用户信息
	 * 
	 * @author czy
	 * @date 2017年8月11日
	 * @param UserInfo
	 *            :用户信息
	 * @return 用户id
	 */
	@PostMapping("insert")
	public JSONResponse<Integer> insert(HttpSession httpSession,
			@RequestBody @Validated(Insert.class) UserInfo userInfo) {
//		if (!departmentService.isManagerOfDeparment(httpSession,
//				userInfo.getDepartment())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = userService.insert(userInfo);
		if (result == null || result < 1) {
			logger.error("新增用户异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 更新用户信息
	 * @author czy
	 * @date 2017年8月11日
	 * @param UserInfo
	 *            用户信息
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("update")
	public JSONResponse<Integer> update(HttpSession httpSession,
			@RequestBody @Validated(Update.class) UserInfo userRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession,
//				userRequest.getDepartment())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = userService.update(userRequest);
		if (result != 1) {
			logger.error("更新用户异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}
	
	/**
     * @Description: 修改用户密码
     * @author czy
     * @date 2017年8月11日
     * @param UserInfo
     *            用户信息
     * @return JSONResponse<Integer>
     */
    @PostMapping("updatePassword")
    public JSONResponse<Integer> updatePassword(HttpSession httpSession,
            @RequestBody UserInfo userRequest) {
//      if (!departmentService.isManagerOfDeparment(httpSession,
//              userRequest.getDepartment())) {
//          logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//          return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//      }
        if(userRequest.getId() == null || userRequest.getPassword() == null) {
            return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
        }
        Integer result = userService.updatePassWord(userRequest);
        if (result != 1) {
            logger.error("更新用户异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
            return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
        } else {
            return success(result);
        }
    }

	/**
	 * @Description: 物理删除用户
	 * @author czy
	 * @date 2017年7月26日
	 * @param id
	 *            用户id
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("delete/physic")
	public JSONResponse<Integer> deletePhysic(HttpSession httpSession,
			@RequestBody @Validated(Delete.class) UserInfo userRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession,
//				userRequest.getDepartment())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = userService.delete(userRequest.getId());
		if (result != 1) {
			logger.error("物理删除用户异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 逻辑删除用户
	 * @author czy
	 * @date 2017年7月26日
	 * @param id
	 *            用户id
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("delete/logic")
	public JSONResponse<Integer> deleteLogic(HttpSession httpSession,
			@RequestBody @Validated(Delete.class) UserInfo userRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession,
//				userRequest.getDepartment())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		userRequest.setValid(0);
		Integer result = userService.update(userRequest);
		if (result != 1) {
			logger.error("逻辑删除用户异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}
	
	@PostMapping("delete/deparment")
    public JSONResponse<Integer> deleteUserDeparment(HttpSession httpSession,
            @RequestBody UserInfo userRequest) {
//      if (!departmentService.isManagerOfDeparment(httpSession,
//              userRequest.getDepartment())) {
//          logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//          return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//      }
        if(userRequest.getId() == null) {
            return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
        }
        Integer result = userService.deleteUserDeparment(userRequest);
        if (result != 1) {
            logger.error("重置用户部门异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
            return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
        } else {
            return success(result);
        }
    }

	/**
	 * @Description: 根据id获取用户详细信息
	 * @author czy
	 * @date 2017年8月11日
	 * @param id
	 *            用户id
	 * @return UserInfo
	 */
	@PostMapping("getUserInfoById")
	public JSONResponse<UserInfo> getUserInfoById(@RequestBody UserInfo userInfo) {
		Integer userId = userInfo.getId();
		if (userId == null) {
			logger.error("获取用户详细信息异常：" + GlobalErrorEnum.PARAM_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		userInfo = userService.getUserInfoById(userId);
		if (userInfo == null) {
			logger.error("获取用户详细信息异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(userInfo);
		}
	}

	/**
	 * @Description: 更新用户角色
	 * @author czy
	 * @date 2017年8月17日
	 * @param UserRoleInfo
	 *            userRoleInfo
	 * @return Integer
	 */
	@PostMapping("update/userRole")
	public JSONResponse<Integer> updateUserRole(
			@RequestBody UserRoleInfo userRoleInfo) {
		if (userRoleInfo.getUserId() == null) {
			logger.error("更新用户角色信息异常：" + GlobalErrorEnum.PARAM_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		Integer result = userRoleService.update(userRoleInfo);
		return success(result);

	}
}
